package ds_industry_2025.ds.ds01.T1

import org.apache.spark.sql.functions.lit
import org.apache.spark.sql.{DataFrame, SparkSession}

import java.text.SimpleDateFormat
import java.util.{Calendar, Properties}

/*
    抽取shtd_store库中user_info的增量数据进入Hive的ods库中表user_info。根据ods.user_info表中operate_time或create_time作
    为增量字段(即MySQL中每条数据取这两个时间中较大的那个时间作为增量字段去和ods里的这两个字段中较大的时间进行比较)，只将新增的数据
    抽入，字段名称、类型不变，同时添加静态分区，分区字段为etl_date，类型为String，且值为当前比赛日的前一天日期（分区字段格式为
    yyyyMMdd）。使用hive cli执行show partitions ods.user_info命令，
 */
object t1 {
  def main(args: Array[String]): Unit = {
    val spark=SparkSession.builder()
      .master("local[*]")
      .appName("t1")
      .config("hive.exec.dynamic.partition.mode","nonstrict")
      .config("spark.serializer","org.apache.spark.serializer.KryoSerializer")
      .config("spark.sql.extensions","org.apache.spark.sql.hudi.HoodieSparkSessionExtension")
      .enableHiveSupport()
      .getOrCreate()

      val conn=new Properties()
      conn.setProperty("user","root")
    conn.setProperty("password","123456")
    conn.setProperty("driver","com.mysql.jdbc.Driver")


      val day=Calendar.getInstance()
    day.add(Calendar.DATE,-1)
    val yesterday=new SimpleDateFormat("yyyyMMdd").format(day.getTime)
    println("昨天的日期为",yesterday)

    spark.sql("use ods")
    spark.table("user_info").createOrReplaceTempView("ods")

    val max_time=spark.sql(
      """
        |select
        |max(if(o.create_time > o.operate_time,o.create_time,o.operate_time)) as time
        |from ods as o
        |""".stripMargin
    ).collect()(0).get(0).toString

    println("最大的时间为",max_time)

    spark.read.jdbc("jdbc:mysql://192.168.40.110:3306/shtd_store?useSSL=false","user_info",conn)
      .createOrReplaceTempView("mysql")

    val result=spark.sql(
      s"""
        |select
        |*
        |from mysql as m
        |where
        |if(m.create_time > m.operate_time,m.create_time,m.operate_time) > cast('$max_time' as timestamp)
        |""".stripMargin)


    result
      .withColumn("etl_date",lit(yesterday))
      .write.mode("append")
      .partitionBy("etl_date")
      .saveAsTable("ods.user_info")











    spark.close()
    }

}
